import React, { useEffect } from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { useRoles } from '../contexts/RolesContext';
import { usePlanType } from '../contexts/PlanTypeContext';
import { useAuth } from '../contexts/AuthContext';
import { isAccountActive, getSuperToken } from '../libs/utils';

// Add a loading component or use an existing one from your project
const LoadingComponent = () => (
  <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
    <div>Loading...</div>
  </div>
);

// Visual Logger Component
const VisualLogger = ({ data }) => {
  useEffect(() => {
    const showDebugPopup = () => {
      const debugContainer = document.createElement('div');
      debugContainer.style.position = 'fixed';
      debugContainer.style.top = '20px';
      debugContainer.style.right = '20px';
      debugContainer.style.backgroundColor = '#f8f9fa';
      debugContainer.style.border = '1px solid #dee2e6';
      debugContainer.style.borderRadius = '4px';
      debugContainer.style.padding = '15px';
      debugContainer.style.maxWidth = '500px';
      debugContainer.style.maxHeight = '80vh';
      debugContainer.style.overflow = 'auto';
      debugContainer.style.zIndex = '9999';
      debugContainer.style.boxShadow = '0 4px 6px rgba(0,0,0,0.1)';
      debugContainer.style.fontFamily = 'monospace';

      const header = document.createElement('div');
      header.style.display = 'flex';
      header.style.justifyContent = 'space-between';
      header.style.marginBottom = '10px';
      header.style.borderBottom = '1px solid #dee2e6';
      header.style.paddingBottom = '5px';
      
      const title = document.createElement('h3');
      title.textContent = 'Route Access Debug';
      title.style.margin = '0';
      title.style.fontSize = '16px';
      title.style.fontWeight = 'bold';
      
      const closeButton = document.createElement('button');
      closeButton.textContent = 'X';
      closeButton.style.border = 'none';
      closeButton.style.background = 'none';
      closeButton.style.cursor = 'pointer';
      closeButton.style.fontSize = '16px';
      closeButton.style.fontWeight = 'bold';
      closeButton.onclick = () => document.body.removeChild(debugContainer);
      
      header.appendChild(title);
      header.appendChild(closeButton);
      debugContainer.appendChild(header);

      const content = document.createElement('div');
      
      Object.entries(data).forEach(([key, value]) => {
        const item = document.createElement('div');
        item.style.marginBottom = '8px';
        
        const keySpan = document.createElement('span');
        keySpan.textContent = `${key}: `;
        keySpan.style.fontWeight = 'bold';
        keySpan.style.color = '#0d6efd';
        
        const valueSpan = document.createElement('span');
        if (typeof value === 'object' && value !== null) {
          valueSpan.textContent = JSON.stringify(value, null, 2);
          valueSpan.style.whiteSpace = 'pre-wrap';
        } else {
          valueSpan.textContent = String(value);
        }
        
        item.appendChild(keySpan);
        item.appendChild(valueSpan);
        content.appendChild(item);
      });
      
      debugContainer.appendChild(content);
      document.body.appendChild(debugContainer);
    };
    
    showDebugPopup();
  }, [data]);
  
  return null;
};

export const PrivateActiveRoute = ({ element: Component, ...rest }) => {
  const location = useLocation();
  const { isAuthenticated, user, isLoading } = useAuth();
  const allowedRoles = useRoles();
  const planType = usePlanType();

  // Wait for authentication status to be determined
  if (isLoading) {
    return <LoadingComponent />;
  }

  // Only check authentication after loading is complete
  if (!isAuthenticated) {
    return (
      <Navigate
        to="/auth/login"
        state={{ from: location.pathname }}
        replace
      />
    );
  }

  // Check if route requires superadmin and if super token exists
  const requiresSuperAdmin = allowedRoles.length === 1 && allowedRoles.includes('superadmin');
  if (requiresSuperAdmin && !getSuperToken()) {
    return (
      <Navigate
        to="/auth/login"
        state={{ from: location.pathname }}
        replace
      />
    );
  }

  // VisualLogger - Early return to display debug info
  const debugData = {
    'Path': location.pathname,
    'isAuthenticated': isAuthenticated,
    'User Role': user?.role || 'undefined',
    'Allowed Roles': allowedRoles,
    'User Plan Type': user?.account?.planType || 'undefined',
    'Required Plan Types': planType,
    'Account Active': user?.account ? isAccountActive(user.account) : 'undefined',
    'Is Super Admin Route': requiresSuperAdmin,
    'Has Super Token': Boolean(getSuperToken()),
  };
  
  // Return the Logger component before checking allowed
  //return <><VisualLogger data={debugData} /><Component {...rest} /></>;

  // The code below will never execute due to the early return above
  // You can comment out or remove the early return when done debugging
  
  const allowed = isAuthenticated && 
    user && 
    allowedRoles.includes(user.role) && 
    (!planType.length || planType.includes(user.account.planType)) &&
    isAccountActive(user.account);

  if (!allowed) {
    return (
      <Navigate
        to="/plan"
        state={{ from: location.pathname }}
        replace
      />
    );
  }

  return <Component {...rest} />;
};